package krow.dev.gunpobus.control.parser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import krow.dev.gunpobus.Constants.Attribute;
import krow.dev.gunpobus.Constants.Value;
import krow.dev.gunpobus.model.StationItem;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

public class StationParser implements IHtmlParser {

	private static Pattern sStationIdPattern = Pattern.compile("(?:stationId=([0-9]+))");

	private List<StationItem> mStationItemList;

	private Map<String, StationItem> mStationItemMap;

	public StationParser() {

		mStationItemList = new ArrayList<StationItem>();

		mStationItemMap = new HashMap<String, StationItem>();
	}

	public List<StationItem> getRouteItemList() {

		return mStationItemList;
	}

	public Map<String, StationItem> getStationItemMap() {
		return mStationItemMap;
	}

	@Override
	public void parse(Source source) throws Exception {

		List<Element> tableElemeList = source.getAllElements(HTMLElementName.TABLE);
		for (Element tableElement : tableElemeList) {
			if (!Value.CLASS_DATABOX.equals(tableElement.getAttributeValue(Attribute.CLASS))) {
				continue;
			}

			List<Element> dataElementList = tableElement.getAllElements(HTMLElementName.TR);
			for (Element dataElement : dataElementList) {
				parseStation(dataElement);
			}
		}
	}

	private void parseStation(Element element) {
		String id = null;
		String name = null;
		String serialNumber = null;

		try {
			Matcher matcher = sStationIdPattern.matcher(element.getAttributeValue(Attribute.CLICK));
			if (matcher.find()) {
				id = matcher.group(1);
			}

			List<Element> spanElementList = element.getAllElements(HTMLElementName.SPAN);
			for (Element spanElement : spanElementList) {

				String className = spanElement.getAttributeValue(Attribute.CLASS);

				if (className.equals(Value.CLASS_STATION_SERIAL)) {
					serialNumber = spanElement.getTextExtractor().toString();
				} else if (className.equals(Value.CLASS_STATION_NAME)) {
					name = spanElement.getTextExtractor().toString();
				}
			}

		} catch (Exception e) {

		}

		if (id != null) {
			StationItem stationItem = new StationItem();
			stationItem.setId(id);
			stationItem.setName(name);
			stationItem.setSerialNumber(serialNumber);

			mStationItemList.add(stationItem);
			mStationItemMap.put(id, stationItem);
		}
	}
}
